package com.rgs.se.bloom;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ren Gaoshuai
 * @ClassName MyBloomFilter1
 * @Description 简单布隆过滤器实现
 * @date 2021-10-11 10:18
 **/
public class MyBloomFilter1 {

    private byte[] data;

    public MyBloomFilter1(int initSize) {
        this.data = new byte[initSize * 2]; // 默认创建大小 * 2 的空间
    }

    /**
     * 向布隆过滤器中 添加key
     * 三个hash函数计算出三个位置，将三个位置标记为1
     */
    public void add(int key) {
        int location1 = Math.abs(hash1(key) % data.length);
        int location2 = Math.abs(hash2(key) % data.length);
        int location3 = Math.abs(hash3(key) % data.length);
        data[location1] = data[location2] = data[location3] = 1;
    }

    /**
     * 是否包含 key
     * 三个位置是否均为1
     *
     */
    public boolean contains(int key) {
        int location1 = Math.abs(hash1(key) % data.length);
        int location2 = Math.abs(hash2(key) % data.length);
        int location3 = Math.abs(hash3(key) % data.length);
        return data[location1] * data[location2] * data[location3] == 1;
    }

    private int hash1(Integer key) {
        return key.hashCode();
    }

    private int hash2(Integer key) {
        int hashCode = key.hashCode();
        return hashCode ^ (hashCode >>> 3);
    }

    private int hash3(Integer key) {
        int hashCode = key.hashCode();
        return hashCode ^ (hashCode >>> 16);
    }

}
